﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SpeakupBackend;
using SpeakupBackend.Classes;

namespace GoogleCalendar
{
    public class EventSynchronizer
    {
        public String Name 
        {
            get
            {
                return m_facade.Name;
            } 

            set
            {
                m_facade.Name = value;
            }
        }
        public String Password 
        { 
            get
            {
                return m_facade.Password;
            }

            set
            {
                m_facade.Password = value;
            }
        }
        
        public Reminder Reminder
        {
            get
            {
                return m_facade.Reminder;
            }

            set
            {
                m_facade.Reminder = value;
            }
        }

        private readonly CalendarFacade m_facade;
        public EventSynchronizer(string name, string password)
        {
            m_facade = new CalendarFacade(name, password);
        }

        public delegate void OnSyncStarted();
        public delegate void OnSyncCompleted(int count);
        public delegate void OnSyncError(Exception ex);

        public event OnSyncStarted SyncStarted;
        public event OnSyncCompleted SyncCompleted;
        public event OnSyncError SyncError;

        private void FireSyncStarted()
        {
            OnSyncStarted deleagateCopy = SyncStarted;
            if (deleagateCopy != null)
            {
                deleagateCopy();
            }
        }
        private void FireSyncCompleted(int count)
        {
            OnSyncCompleted deleagateCopy = SyncCompleted;
            if (deleagateCopy != null)
            {
                deleagateCopy(count);
            }
        }
        private void FireSyncError(Exception ex)
        {
            OnSyncError deleagateCopy = SyncError;
            if (deleagateCopy != null)
            {
                deleagateCopy(ex);
            }
        }

        public int Synchronize(BackendContext ctx)
        {
            try
            {
                FireSyncStarted();

                var events = from n in ctx.Classes
                             where n.CurrentStatus == ClassStatus.Reserved
                             select n;

                m_facade.ClearEvents();
                m_facade.AddEvents(events.ToList());

                FireSyncCompleted(events.Count());
                return events.Count();
            }
            catch (Exception ex)
            {
                FireSyncError(ex);                
            }
            return 0;
        }
    }
}
